﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                int port = 2000;
                IPEndPoint ipend = new IPEndPoint(ip, port);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(ipend);
                Console.WriteLine("等待客户端连接");
                socket.Listen(0);
                Socket newSocket = socket.Accept();
                Console.WriteLine("与客户端建立连接");

                //发送和接收数据...
                //使用NewworkStream
                //接收数据
                //NetworkStream ns = new NetworkStream(newSocket);
                byte[] recB=new byte[1024];
                //int bs=ns.Read(recB, 0, recB.Length);
                //ns.Flush();
                //string strRec = Encoding.UTF8.GetString(recB, 0, bs);
                //Console.WriteLine("服务器收到的数据："+strRec);
                //ns.Close();
                //newSocket.Close();
                //Socket
                int bs=newSocket.Receive(recB,recB.Length, SocketFlags.None);
                string strRec = Encoding.UTF8.GetString(recB, 0, bs);
                Console.WriteLine("服务器收到的数据："+strRec);
                newSocket.Close();
                socket.Close();

                Console.WriteLine("连接关闭");
                Console.ReadLine();
            }
            catch (SocketException e)
            {
                Console.WriteLine("出现Socket异常：{0}",e);
                Console.ReadLine();
            }
        }
    }
}
